<?php
class PostsController extends CController {
	public function filters() {
		return array(
				'accessControl'
		);
	}

	public function accessRules() {
		return array(
			array(
				'allow',
				'expression' => ForumMembers::isAdmin()
			),
			array(
				'deny',
			),
		);
	}
	
	public function actionIndex() {
		$criteria = new CDbCriteria;
		$criteria->order = 'postId DESC';
		$with = array('categories');
		// Get the count of all posts
		$postsCount = Posts::model()->with($with)->count($criteria);
		// Pagination
		$pages = new CPagination($postsCount);
		$pages->pageSize = Yii::app()->params['manageListPerPage'];
		$pages->applyLimit($criteria);
		// Posts' data
		$posts = Posts::model()->findAll($criteria);

		$topics = TermsTaxonomy::model()->getTopics();
		$this->render('postsListing', array(
				'posts' => $posts, 
				'pages' => $pages,
                'topics' => $topics
			)
		);
		exit;
	}
	
	public function actionSearch() {
		if(isset($_GET['key'])) {
			$key = trim(urldecode($_GET['key']));

			$criteria = new CDbCriteria;
			$criteria->order = 'postId DESC';
			$criteria->condition = 'postTitle LIKE "%'.$key.'%"';
			$with = array('categories');
			// Get the count of all posts
			$postsCount = Posts::model()->with($with)->count($criteria);
			// Pagination
			$pages = new CPagination($postsCount);
			$pages->pageSize = 10;
			$pages->params = array('key' => urlencode($key));
			$pages->applyLimit($criteria);
			// Posts' data
			$posts = Posts::model()->with($with)->findAll($criteria);

            $topics = TermsTaxonomy::model()->getTopics();
			$this->render('postsListing', array(
					'posts' => isset($posts) ? $posts : null,
					'pages' => $pages,
					'key' => htmlspecialchars($key),
                    'topics' => $topics
				)
			);
		}
	}
	
	public function actionHots() {
		$optionName = 'hotPosts';
		$option = Options::model()->findOptionByName($optionName);
		if(isPost()) {
			$option->optionValue = implode(',', Options::filterCommaValue($_POST[$optionName]));
			if($option->save()) {
				Yii::app()->cache->set('hotPosts', $this->createWidget('HotPosts')->renderContent(true));
			}
		}
		$hotPosts = explode(',', $option->optionValue);
		$posts= Posts::model()->findAllByPk($hotPosts);

		$this->render('hots', array('posts' => $posts, 'hotPosts' => $hotPosts, 'option' => $option));
	}

	public function actionEdit() {
		// Get post by specified ID
		$post = Yii::app()->user->hasFlash('post') ? unserialize(Yii::app()->user->getFlash('post')) : $this->loadPost();
		$post->scenario = 'edit';
		// Process the requested form's data
		if(isPost()) {
			$post->attributes = $_POST['Posts'];
			if(isset($_POST['submitPost'])) {
				if(isset($_POST['category']) && $_POST['category'] != '') {
					$post->categoryId = $_POST['category'];
				}
				if($post->validate()) {
					if(isset($_POST['topic']) && isset($_POST['category']) && !$post->hasErrors() && $post->save(false)) {
						// Save the topic of post data
						if($_POST['topic'] != '') {
							$topic2post = new TermsRelationships;
							$topic2post->objectId = $post->postId;
							$topic2post->subjectId = $_POST['topic'];
						}
						$origRecs = TermsRelationships::model()->with('topics')->findAllByAttributes(array('objectId' => $post->postId));
						if($origRecs !== null) {
							foreach($origRecs as $row) {
								$row->delete();
							}
						}
						if(isset($topic2post) && $topic2post !== null) {
							$topic2post->save();
						}
						// Save the category of post data
						$category2post = new TermsRelationships;
						$category2post->objectId = $post->postId;
						$category2post->subjectId = $_POST['category'];
						$origRecs = TermsRelationships::model()->with('categories')->findAllByAttributes(array('objectId' => $category2post->objectId));
						if($origRecs !== null) {
							foreach($origRecs as $row) {
								$row->delete();
							}
						}
						$category2post->save();
					}
				}
			}
		}
		
		// Get the categories and topics
		$categories = TermsTaxonomy::model()->getCategories(true);
		$topics = TermsTaxonomy::model()->getTopics();

		$this->render('postEdit', array(
				'post' => $post,
				'categories' => $categories,
				'topics' => $topics
			)
		);
	}

	public function actionPostNew() {
		$post = new Posts;
		
		// Process the requested form's data
		if(isPost()) {
			$post->attributes = $_POST['Posts'];
			if(isset($_POST['submitPost'])) {
				$post->postDate = time();
				$post->postAuthor = Yii::app()->user->id;
//				$post->postStatus = Posts::STATUS_PUBLISHED;
				if(isset($_POST['category']) && $_POST['category'] != '') {
					$post->categoryId = $_POST['category'];
				}
				if($post->validate()) {
					if(isset($_POST['topic']) && isset($_POST['category']) && !$post->hasErrors() && $post->save(false)) {
						// Save the topic of post's data. Not required
						if($_POST['topic'] != '') {
							$topic2post = new TermsRelationships;
							$topic2post->objectId = $post->postId;
							$topic2post->subjectId = $_POST['topic'];
							$topic2post->save();
						}
						
						// Save the category of post's data. Required
						$category2post = new TermsRelationships;
						$category2post->objectId = $post->postId;
						$category2post->subjectId = $_POST['category'];
						$category2post->save();
	
						$message = '文章成功发布。点击'.CHtml::link('这里', array('/posts/view', 'id' => $post->postId), array('target' => '_blank')).'查看';
						Yii::app()->user->setFlash('message', $message);
	                    
						$this->redirect(array('admin/posts/edit', 'id' => $post->postId));
					}
				}
			}
		}
		// Get the categories and topics
		$categories = TermsTaxonomy::model()->getCategories(true);
		$topics = TermsTaxonomy::model()->getTopics();
		$this->render('postNew', array(
				'post' => $post,
				'categories' => $categories,
				'topics' => $topics
			)
		);
	}

	public function actionCategories() {
		$count = 0;
		$categories = TermsTaxonomy::model()->getCategories(false, $count, true);
		
		$this->render('categories', array(
				'categories' => $categories,
				'count' => $count
			)
		);
	}
	
	public function actionCategoryEdit() {
		$termTaxonomyId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

		if(isPost()) {
			// Save category name
			$termName = $_POST['name'];
			$term = Terms::model()->with(array('taxonomy' => array('condition' => 'termTaxonomyId = '.$termTaxonomyId)))->find();
			$term->name = $termName;
			$term->save();
			// Save category picture
			$criteria = new CDbCriteria;
			$criteria->condition = 'termTaxonomyId = '.$termTaxonomyId.' AND metaKey = "'.TermsTaxonomyMeta::KEY_CATEGORY_PIC.'"';
			$categoryPic = TermsTaxonomyMeta::model()->exists($criteria) ? 
				TermsTaxonomyMeta::model()->find($criteria) : new TermsTaxonomyMeta;
			$categoryPic->termTaxonomyId = $termTaxonomyId;
			$categoryPic->metaKey = TermsTaxonomyMeta::KEY_CATEGORY_PIC;
			$this->picProcess($categoryPic);
			$categoryPic->save();
			// Save top post
			$criteria = new CDbCriteria;
			$criteria->condition = 'termTaxonomyId = '.$termTaxonomyId.' AND metaKey = "'.TermsTaxonomyMeta::KEY_TOP_POST.'"';
			$topPost = TermsTaxonomyMeta::model()->exists($criteria) ? 
				TermsTaxonomyMeta::model()->find($criteria) : new TermsTaxonomyMeta;
			$topPost->termTaxonomyId = $termTaxonomyId;
			$topPost->metaKey = TermsTaxonomyMeta::KEY_TOP_POST;
			$topPost->metaValue = $_POST['topPost'];
			$topPost->save();
		}

		$_categoryPic = new TermsTaxonomyMeta;
		$_topPost = new TermsTaxonomyMeta;
		
		$category = TermsTaxonomy::model()->find('termTaxonomyId = :termTaxonomyId AND taxonomy = :taxonomy', 
			array('termTaxonomyId' => $termTaxonomyId, 'taxonomy' => TermsTaxonomy::TAXONOMY_CATEGORY)
		);

		$this->render('categoryEdit', array(
				'category' => $category,
				'categoryPic' => $_categoryPic,
				'topPost' => $_topPost
			)
		);
	}

        public function actionDelete() {
            $postId = isset($_GET['id']) ? (int)$_GET['id'] : -1;
            
            if($postId) {
                        $post = Posts::model()->findByPk($postId);
			if($post !== null) {
				if($post->delete()) {
                                    Comments::model()->deleteAll('postId = '.$post->postId);
                                    $message = '文章删除成功。';
                                    Yii::app()->user->setFlash('message', $message);
                                    $this->redirect(Yii::app()->request->urlReferrer);
                                }
			}
            }
        }

	private function picProcess(&$termTaxonomyMeta, $save = false, $ctrl = 'categoryPic') {
		// Upload file now
		$uploadedPic = CUploadedFile::getInstance($termTaxonomyMeta, $ctrl);
		if(is_uploaded_file(isset($uploadedPic->tempName) ? $uploadedPic->tempName : '')) {
			$tmpPath = UPLOADS_TEMP.'/'.randStr();
			if($uploadedPic->saveAs($tmpPath)) {
				// Crop the image and save as file
				Yii::import('application.extensions.image.Image');
				$image = new Image($tmpPath);
				$ext = '.jpg';
				$avatar = randStr();
				// Make the thumb
				$avatarFn = $avatar.'_'.TermsTaxonomyMeta::CATEGORY_PIC_SUFFIX_L.$ext;
				$savePath = UPLOADS_CATEGORIES_PICS.'/'.$avatarFn;
				$flag = $image->resize(
					TermsTaxonomyMeta::CATEGORY_PIC_WIDTH_L,
					TermsTaxonomyMeta::CATEGORY_PIC_HEIGHT_L
				)->save($savePath);
				$avatarFn = $avatar.'_'.TermsTaxonomyMeta::CATEGORY_PIC_SUFFIX_M.$ext;
				$savePath = UPLOADS_CATEGORIES_PICS.'/'.$avatarFn;
				$flag = $flag && $image->resize(
					TermsTaxonomyMeta::CATEGORY_PIC_WIDTH_M,
					TermsTaxonomyMeta::CATEGORY_PIC_HEIGHT_M
				)->save($savePath);
				$termTaxonomyMeta->metaValue = $flag ? $avatar : $termTaxonomyMeta->metaValue;
				if($save) {
					return $termTaxonomyMeta->save();
				}
			}
		}
	}

    public function actionUpdateCategory() {
        if(isAjax()) {
            if(isset($_POST['postId']) && isset($_POST['categoryId'])) {
                $postId = (int)$_POST['postId'];
                $categoryId = (int)$_POST['categoryId'];
                $post = Posts::model()->findByPk($postId);

                // Save the category of post data
                $category2post = new TermsRelationships;
                $category2post->objectId = $post->postId;
                $category2post->subjectId = $categoryId;
                $origRecs = TermsRelationships::model()->with('categories')->findAllByAttributes(array('objectId' => $category2post->objectId));
                if($origRecs !== null) {
                    foreach($origRecs as $row) {
                        $row->delete();
                    }
                }
                if($category2post->save()) {
                    echo 1;
                    return ;
                }
            }
        } 
        echo 0;
        return ;
    }

        public function actionUpdateTopic() {
        if(isAjax()) {
            if(isset($_POST['postId']) && isset($_POST['topicId'])) {
                $postId = (int)$_POST['postId'];
                $topicId = (int)$_POST['topicId'];
                $post = Posts::model()->findByPk($postId);

                // Save the topic of post data
                $topic2post = new TermsRelationships;
                $topic2post->objectId = $post->postId;
                $topic2post->subjectId = $topicId;
                $origRecs = TermsRelationships::model()->with('topics')->findAllByAttributes(array('objectId' => $topic2post->objectId));
                if($origRecs !== null) {
                    foreach($origRecs as $row) {
                        $row->delete();
                    }
                }
                if($topic2post->save()) {
                    echo 1;
                    return ;
                }
            }
        }
        echo 0;
        return ;
    }

	protected function loadPost($id = null) {
		if($id !== null || isset($_GET['id'])) {
			$post = Posts::model()->findbyPk($id !== null ? $id : (int)$_GET['id']);
		}
		
		if($post === null) {
			throw new CHttpException(404, 'The requested post does not exist.');
		}
		return $post;
	}
}
